package com.calsoft.Hops_Mobile_Tablet.util;
/*
 * User: Minh Diep
 * Date: 6/25/13
 * Time: 6:25 PM
 */

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.calsoft.Hops_Mobile_Tablet.LoginActivity;
import com.calsoft.Hops_Mobile_Tablet.base.App;

public class SessionManager {

    private SharedPreferences sPrefs;
    private SharedPreferences.Editor sPrefsEditor;

    private SharedPrefs sPresEditorMainSession;
    private Context context;

    private static final String PREFS_SESSION_MANAGER = "com.calsoft.hops.mobile.session.manager.sprefs";
    private static final String IS_LOGIN = "com.calsoft.hops.mobile.session.manager.sprefs.IsLoggedIn";
    public static final String KEY_EMAIL = "com.calsoft.hops.mobile.session.manager.sprefs.email";

    public SessionManager(Context context){
        this.context = context;
        sPrefs = context.getSharedPreferences(PREFS_SESSION_MANAGER, 0);
        sPrefsEditor = sPrefs.edit();
        sPresEditorMainSession = new SharedPrefs(context);
    }

    /**
     * Create login session
     * */
    public void createLoginSession(String email){
        // Storing login value as TRUE
        sPrefsEditor.putBoolean(IS_LOGIN, true);

        // Storing email in pref
        sPrefsEditor.putString(KEY_EMAIL, email);

        // commit changes
        sPrefsEditor.commit();
    }


    public String getUserEmail(){
        return sPrefs.getString(KEY_EMAIL, null);
    }

    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * Else won't do anything
     * */
    public void checkLogin(){
        // Check login status
        if(!this.isLoggedIn()){
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(context, LoginActivity.class);
            // Closing all the Activities
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

            // Add new Flag to start new Activity
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            context.startActivity(i);
        }
    }

    /**
     * Clear session details
     * */
    public void logoutUser(){
        // Clearing all data from Shared Preferences
        sPrefsEditor.clear();
        sPrefsEditor.commit();

        // Clearing all data from Main Session
        sPresEditorMainSession.clear();

        // After logout redirect user to Loing Activity
        Intent i = new Intent(context, LoginActivity.class);
        // Closing all the Activities
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

        // Add new Flag to start new Activity
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        context.startActivity(i);
    }

    public boolean isLoggedIn(){
        return sPrefs.getBoolean(IS_LOGIN, false);
    }



}
